package org.lsp.champs;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Exchanger;

import org.lsp.io.files.XML;
import org.lsp.io.logger.SysLogger;

import res.SysRes;

public abstract class ChampionManager {
	private static final HashMap<String, Support> champions = new HashMap<String, Support>();

	protected static final Support getChampionByName(final String championName) {
		Support ret;
		if (!ChampionManager.champions.isEmpty()) {
			ret = (Support) ChampionManager.champions.get(championName).clone();
		} else {
			ChampionManager.importChampions();
			ret = ChampionManager.getChampionByName(championName);
		}

		return ret;
	}

	public static final void importChampions() {
		final ArrayList<HashMap<String, String>> adcs = XML.getAllOfType(
				SysRes.string(3), Paths.get(SysRes.string(2)).toFile()), sups = XML
				.getAllOfType(SysRes.string(4), Paths.get(SysRes.string(2))
						.toFile());

		final Exchanger<Object> lock = new Exchanger<>();

		new Thread() {

			@Override
			public void run() {
				for (final HashMap<String, String> t : adcs) {
					final String name = t.get("NAME");
					ChampionManager.champions.put(name, new ADCarry(name));
				}
				try {
					lock.exchange(null);
				} catch (final InterruptedException e) {
					SysLogger.log(e, "ERR10", SysLogger.Level.CRASH);
				}
			}
		}.start();

		for (final HashMap<String, String> t : sups) {
			final String name = t.get("NAME");
			ChampionManager.champions.put(name, new Support(name));
		}

		try {
			lock.exchange(null);
		} catch (final InterruptedException e) {
			SysLogger.log(e, "ERR11", SysLogger.Level.CRASH);
		}
		new Thread() {

			@Override
			public void run() {
				for (final HashMap<String, String> t : sups) {
					String counterName = "";
					for (int i = 1; t.get((counterName = "COU" + i)) != null; i++) {
						ChampionManager.getChampionByName(t.get("NAME"))
								.addCounter(t.get(counterName));
					}
				}
				try {
					lock.exchange(null);
				} catch (final InterruptedException e) {
					SysLogger.log(e, "ERR12", SysLogger.Level.CRASH);
				}
			}
		}.start();

		for (final HashMap<String, String> t : adcs) {
			String counterName = "";
			for (int i = 1; t.get((counterName = "COU" + i)) != null; i++) {
				ChampionManager.getChampionByName(t.get("NAME")).addCounter(
						t.get((counterName)));
				((ADCarry) ChampionManager.getChampionByName(t.get("NAME")))
						.addSupport(t.get("SUP" + i));
			}
		}

		try {
			lock.exchange(null);
		} catch (final InterruptedException e) {
			SysLogger.log(e, "ERR13", SysLogger.Level.CRASH);
		}
	}
}
